import Adv from "./adv";
import md5 from 'js-md5';
import Brand from "./component/brand";
import Account from "./account";
import Diect from "./diect";
import Market from "./market";
import SchedulePrice from "./schedulePrice";
import Creativor from "./creativite";
import Position from "./position";


function ImageList() {

}


export const MAIN_JUMP_INFO = 'main_jump_info';





export function setAdvName(state: any) {
  state.modal.adgroupName = '{{版位名称}}_{{日期}}_{{时分秒}}';
  state.modal.creativor.name = '{{版位名称}}_{{日期}}_{{时分秒}}_创意'
}

function makeAddZero(value: any) {
  value = value + '';
  return value.length == 1 ? '0' + value : value;
}


export function getRealAdvName(state: any, name?: string) {
  const regMath: any = makeAdvNameReg(state);
  let adgroupName = (name || state.modal.adgroupName) as any;
  return adgroupName.replace(/_?{{([^}}]+)}}/g, (_: any, match: any) => { return regMath[match] ? regMath[match] : '' }).replace(/^_/, '');
}


export function makeAdvNameReg(state: any) {
  const { position, diect } = state.modal;
  const newdate = new Date();
  let month: any = makeAddZero(newdate.getMonth() + 1);
  let date = makeAddZero(newdate.getDate());
  let hour = makeAddZero(newdate.getHours());
  let min = makeAddZero(newdate.getMinutes());
  let second = makeAddZero(newdate.getSeconds());
  const regMath = {
    '日期': '_' + (month + date),
    '时分秒': '_' + hour + min + second,
    // 不要搜索场景
    '版位名称': '_' + position.name.replace(/搜索场景|、搜索场景/, ''),
    '账户ID': '_ACCOUNT_CODE',
    '定向包名称': '_' + diect.outTargetingName,
  };
  return regMath;
}

// function


export function cloneMarketComponentAndInjectAccount(account: Account, marketComponents: any) {
  const cloneMarketComponent: any = {};
  Object.keys(marketComponents).map(key => {
    const component = marketComponents[key];
    const clone = component.clone();
    clone.account = account;
    cloneMarketComponent[key] = clone;
  });
  return cloneMarketComponent;

}


export function componentInjectComponents(marketComponents: any) {
  // marketComponents.
}


export function createCreateGroupBody(state: any) {
  const { accounts, modal } = state;
  const { creativor, marketComponents } = modal as Adv;
  return accounts.map((account: any) => {
    const { market, wechatChannels } = account;
    const productInfo = market.productInfo;
    // 创意自增id;
    let creativeIndex = 1;
    const way = creativor.way;
    // 品牌形象是否视频号
    const isWxChannels = creativor.brandType === 'WECHAT_CHANNELS';
    // 是否指定组件
    const unSpecifiedForm = creativor.unSpecifiedForm;
    const getJumpComponet = modal.marketComponents[MAIN_JUMP_INFO];
    const isComponentCreative = creativor.isComponentCreative;

    if (getJumpComponet) {
      // 设置品牌形象
      getJumpComponet.brand_type = creativor.brandType;
    }
    const getBrandComponent = modal.marketComponents['brand'];
    // 创意组件(对接TX) https://developers.e.qq.com/v3.0/docs/api/dynamic_creatives/get
    function createComponent(options = {}) {

      const { accountCode } = options as any;
      const creative_components: any = {};
      const mainJumpComponent = marketComponents[MAIN_JUMP_INFO];
      // 二期 再去实现
      // const cloneMarketComponents = cloneMarketComponentAndInjectAccount(account, marketComponents);
      // console.log(cloneMarketComponents, 'cloneMarketComponents');
      Object.keys(marketComponents).map(key => {
        const component = marketComponents[key] as any;
        // 由于落地页是多个的，无法直接从组件获取，改从accounts
        const account = accounts.find((account: any) => account.accountCode == accountCode);

        // 品牌
        account.loadPage.brand_type = mainJumpComponent ? mainJumpComponent.brand_type : creativor.brandType;
        // 落地页 落地页的数据来自于account
        if (key === MAIN_JUMP_INFO) {
          const querys: any = [];
          account.jumpInfo.map((component: any) => {
            querys.push({
              value: component.query({
                page_type: mainJumpComponent.value.page_type,
                override_canvas_head_option: mainJumpComponent.value.override_canvas_head_option,
              })
            })
          })
          creative_components[MAIN_JUMP_INFO] = querys;
          return;
        }
        // 品牌组件特殊处理 如果是视频号，数据源从account.wechatChannels 获取
        if (isWxChannels && key === 'brand') {
          const wechatChannels = account.wechatChannels ? account.wechatChannels || {} : {};
          const brand = new Brand({
            value: {
              brand_image_id: "" + wechatChannels.id,
              brand_name: "" + wechatChannels.name
            }
          });
          // 设置品牌形象
          brand.brand_type = creativor.brandType;
          brand.value = {
            brand_image_id: "" + wechatChannels.id,
            brand_name: "" + wechatChannels.name,
            brand_url: ""
          }
          const componentQuery = brand.query();
          // creative_components.brand
          componentQuery && (creative_components[component.tx_component] = [{ value: componentQuery }])
          return;
        }
        // 如果需要上传跳转信息
        if (component.children && component.children.jump_info && key != 'brand') {

          const componentQuery = component.query();
          const querys: any = []
          account.jumpInfo.map((component: any) => {
            const jumpInfoQuery = component.query({
              page_type: mainJumpComponent.value.page_type,
              override_canvas_head_option: mainJumpComponent.value.override_canvas_head_option,
            })
            let other = {
            }
            // 如果是文字链接 需要配置落地页
            other = jumpInfoQuery && componentQuery ? {
              jump_info: jumpInfoQuery
            } : {};
            querys.push({
              value: Object.assign(componentQuery || {}, other)
            })
          });
          componentQuery && (creative_components[component.tx_component] = querys);
          return;
        }

        // 视频号
        if (key === 'wechat_channels') {
          // if (requireFloatZone) { creative_components[component.tx_component] = undefined; } else {
          const wechatChannels = account.wechatChannels ? account.wechatChannels || {} : {};
          creative_components[component.tx_component] = wechatChannels.id ? [{
            value: {
              finder_object_visibility: false,
              username: "" + wechatChannels.id,
              // finder_object_visibility: false,
            }
          }] : undefined;

          // }

          return;
        }
        // 常规组件上报逻辑
        if (component.tx_component) {
          const componentQuery = component.query();
          componentQuery && (creative_components[component.tx_component] = [{
            value: Object.assign(componentQuery)
          }]);
        }
      });
      return creative_components;
    }
    return {
      accountCode: account.accountCode,
      productCatalogId: productInfo.productCatalogId,
      productId: productInfo.productId,
      wechatChannelsId: wechatChannels.id,
      creativeArrayList: creativor.groups.map((group) => {
        return {

          creativeList: group.creative.map((creative) => {
            const creativename = creativor.name + '_00' + creativeIndex;
            creativeIndex++;
            const creativeMediaList: Array<any> = [];
            const creative_components = createComponent({
              accountCode: account.accountCode,
              account
            });
            // 文案组件
            if (creative.textComponent && creative.textComponent.length) {
              const querys: any = [];
              creative.textComponent.map(component => {
                const query = component.query();
                querys.push({
                  value: query
                });
                creativeMediaList.push({
                  mediaType: 5,
                  accountCode: account.accountCode,
                  previewUrl: component.content,
                })

              })
              creative_components['description'] = querys;

            }
            // 不指定组件
            if (unSpecifiedForm && creative.libMedia) {

              creative.libMedia.mediaMap((component: any) => {
                const tx_component = component.meta_type == 'image' ? 'image' : 'video';
                if (!creative_components[tx_component]) {
                  creative_components[tx_component] = [];
                }

                creative_components[tx_component].push({
                  value: component.query()
                })
                creativeMediaList.push({
                  accountCode: component.accountCode || account.accountCode,
                  mediaId: component.media_id,
                  mediaName: component.mediaName,
                  previewUrl: component.media_url,
                  keyFrameImageUrl: component.keyFrameImageUrl,
                  mediaSignature: component.mediaSignature,
                  mediaWidth: component.mediaWidth,
                  mediaHeight: component.mediaHeight,
                  mediaType: component.meta_type === 'image' ? 6 : 7,
                  fileSize: component.fileSize,
                })
              });



            }

            // 媒体组件
            if (creative.mediaComponent && creative.mediaComponent.length && !unSpecifiedForm) {

              const querys: any = [];
              creative.mediaComponent.map(component => {
                querys.push({
                  value: component.query()
                });
                component.mediaMap((component: any) => {
                  // isComponentCreative && creativeMediaList.push({
                  //   accountCode: component.accountCode || account.accountCode,
                  //   mediaId: component.media_id,
                  //   mediaName: component.mediaName,
                  //   previewUrl: component.media_url,
                  //   keyFrameImageUrl: component.keyFrameImageUrl,
                  //   mediaSignature: component.mediaSignature,
                  //   mediaWidth: component.mediaWidth,
                  //   mediaHeight: component.mediaHeight,
                  //   mediaType: component.meta_type === 'image' ? 6 : 7,
                  //   fileSize: component.fileSize,
                  // })
                  creativeMediaList.push({
                    accountCode: component.accountCode || account.accountCode,
                    mediaId: component.media_id,
                    mediaName: component.mediaName,
                    previewUrl: component.media_url,
                    keyFrameImageUrl: component.keyFrameImageUrl,
                    mediaSignature: component.mediaSignature,
                    mediaWidth: component.mediaWidth,
                    mediaHeight: component.mediaHeight,
                    mediaType: component.meta_type === 'image' ? 1 : 2,
                    fileSize: component.fileSize,
                  })
                })
              });
              const tx_component = creative.mediaComponent[0].tx_component;
              creative_components[tx_component] = querys;

            }
            // 品牌形象组件 且不是视频号 因为微信视频号无需用·creativeMediaList·传给后端
            if (getBrandComponent && !isWxChannels) {
              const value = (getBrandComponent as any).value;

              creativeMediaList.push({
                accountCode: getBrandComponent.accountCode || account.accountCode,
                previewUrl: value.brand_url,
                mediaName: value.brand_name,
                mediaWidth: value.width,
                mediaHeight: value.height,
                mediaId: getBrandComponent.splitId(value.brand_image_id),
                mediaType: creativor.brandType,
              })
            }
            return {
              derivedCreativeSwitch: creative.derivedCreativeSwitch,
              creativeName: creativename,
              creativeComponents: JSON.stringify(creative_components),
              deliveryMode: creativor.deliveryMode,
              // derivedCreativeSwitch
              creativeTemplateId: creativor.creativeTemplateId,
              pageType: getJumpComponet ? getJumpComponet.value.page_type : undefined,
              creativeMediaList
            }
          })
        }
      })

    }

  })
}


function createAdvBody(state: any) {
  const { accounts, modal } = state;
  const { market, position, schedulePrice, uuid, diect } = modal;
  const scene_spec = position.scene_spec;
  let hasGender = true;
  if (Array.isArray(diect.gender)) {
    hasGender = diect.gender.length > 0;
  }
  if (!diect.gender) {
    hasGender = false;
  }
  const targetingInfo = diect.query();
  return {
    "adgroupId": modal.adgroupId,     //广告ID，修改时必传
    "batchId": modal.batchId ? modal.batchId : md5(uuid),  //批次ID
    "adgroupName": modal.adgroupName,     //广告名称
    "marketingGoal": market.marketingGoal,    //营销目的:MARKETING_GOAL_PRODUCT_SALES-商品销售
    "marketingTargetType": market.marketingTargetType,    //推广产品:MARKETING_TARGET_TYPE_CONSUMER_PRODUCT-商品;MARKETING_TARGET_TYPE_WECHAT_CHANNELS_LIVE-视频号直播
    "siteSetType": position.siteSetType,     //版位类型：1-自动版位；2-特定版位
    "accountCode": accounts[0].accountCode,     //首选账户，获取创意规格账户
    "siteSet": position.siteSet.join(','),     //版位,特定版位必传
    "releaseDateType": schedulePrice.releaseDateType,     //投放日期类型：1-一年；2-半年；3-3个月；4-1个月；5-其他
    "releaseTimeType": schedulePrice.releaseTimeType,     //投放时间：1:全天；2：特定时间段
    "releaseBeginDate": schedulePrice.releaseBeginDate, //投放开始日期
    "releaseEndDate": schedulePrice.releaseEndDate,
    // "releaseBeginDate": schedulePrice.releaseBeginTime, //投放开始日期
    // "releaseEndDate": schedulePrice.releaseEndTime,   //投放结束日期
    "firstDayBeginTime": schedulePrice.firstDayBeginTime,       //首日开始投放时间
    "releaseBeginTime": schedulePrice.releaseBeginTime,      //投放开始时间
    "releaseEndTime": schedulePrice.releaseEndTime,        //投放结束时间
    "bidMode": schedulePrice.bidMode,                     //BID_MODE_CPM/BID_MODE_OCPM
    // 默认
    "optimizationGoal": "OPTIMIZATIONGOAL_ECOMMERCE_ORDER",    //广告优化目标:OPTIMIZATIONGOAL_ECOMMERCE_ORDER:下单

    "bidScene": schedulePrice.bidScene,    //出价类型:SMART_BID_TYPE_CUSTOM-常规投放-稳定投放;SMART_BID_TYPE_SYSTEMATIC-优先最大转化
    // 可能要这样
    // schedulePrice.bidScene === 'SMART_BID_TYPE_CUSTOM' ? null : schedulePrice.dailyBudget
    "dailyBudget": schedulePrice.dailyBudget,      //广告日预算,为空或0为 不限
    "bidAmount": schedulePrice.bidScene === 'SMART_BID_TYPE_SYSTEMATIC' ? null : schedulePrice.bidAmount,      //出价
    "autoAcquisitionEnabled": schedulePrice.bidMode === 'BID_MODE_CPM' || schedulePrice.bidScene == 'SMART_BID_TYPE_SYSTEMATIC' ? 0 : schedulePrice.autoAcquisitionEnabled,   //一键起量开关:0-关；1-开
    // 单位为分
    "autoAcquisitionBudget": schedulePrice.autoAcquisitionBudget,  //一键起量预算

    "deepConversionSpec": schedulePrice.deepConversionSpec,       //深度转化优化：0-关；1-开
    "deepConversionFailTry": schedulePrice.deepOptimalWarn,    //原深度辅助ROI未开白时重试：1-上传失败；2-深度转化优化关闭；
    "deepConversionGoal": schedulePrice.deepConversionGoal,
    "deepConversionType": schedulePrice.deepConversionType,  //DEEP_CONVERSION_WORTH:优化 ROI;DEEP_CONVERSION_WORTH_ADVANCED:深度辅助优化 ROI
    "deepConversionExpectedRoi": schedulePrice.deepConversionExpectedRoi,  //期望ROI
    "outTargetingId": diect.outTargetingId,     //定向 id,
    "targetingAccountCode": diect.targetingAccountCode,
    "targetingInfo": JSON.stringify(targetingInfo),

    // "{\"age\": [{\"max\": 18,\"min\": 14}],\"geo_location\": {\"location_types\":[\"LIVE_IN\"],\"regions\":[100000,100001]},\"gender\":[\"MALE\",\"FEMALE\"]}",   //定向信息
    "adgroupSceneSpecVo": {
      "wechatPosition": scene_spec.wechat_position.value.join(','),  //微信公众号与小程序定投，用”,”分割
      "wechatChannelsScene": scene_spec.wechat_channels_scene.value.join(','),     //微信视频号定投，用”,”分割
      "officialAccountMediaCategory": scene_spec.wechat_scene.official_account_media_category.join(','),    //公众号媒体类型，用”,”分割
      "miniProgramAndMiniGame": scene_spec.wechat_scene.mini_program_and_mini_game.join(','),          //小程序小游戏流量类型，用”,”分割
      "payScene": scene_spec.wechat_scene.pay_scene.join(','),       //订单详情页消费场景，用”,”分割
      "mobileUnionCategory": scene_spec.mobile_union_category.value.join(','), //优量汇广告展示场景，当且仅当投放优量汇流量时（site_set = SITE_SET_MOBILE_UNION）时可以使用
      "unionPositionPackage": scene_spec.union_position_package.value.join(','),    //定投联盟流量包列表，一个广告最多可选择 20 个定投流量包，且该广告所有流量包关联的广告位数量不得超过 500 个
      "excludeUnionPositionPackage": scene_spec.exclude_union_position_package.value.join(','), //屏蔽联盟流量包列表，一个广告最多可选择 20 个屏蔽流量包，且该广告所有流量包关联的广告位数量不得超过 500 个
      "flowOptimizationEnabled": scene_spec.mobile_union_category.value.length ? scene_spec.flow_optimization_enabled : 0,   //是否使用自动流量优选
    },
    "accountAdgroupVoList": createCreateGroupBody(state)
  }

}

// 广告基础数据(非创意)回显
export function backDisaplyAdvBaseInfo(state: any, info: any) {
  const adgroupSceneSpecVo = info.adgroupSceneSpecVo;
  state.modal.adgroupId = info.adgroupId;
  state.modal.batchId = info.batchId;
  state.modal.adgroupName = info.adgroupName;
  // 广告定向
  const officialAccountMediaCategory = (adgroupSceneSpecVo.officialAccountMediaCategory || '') ? (adgroupSceneSpecVo.officialAccountMediaCategory || '').split(',') : [];
  const miniProgramAndMiniGame = (adgroupSceneSpecVo.miniProgramAndMiniGame || '') ? (adgroupSceneSpecVo.miniProgramAndMiniGame || '').split(',') : [];
  const payScene = (adgroupSceneSpecVo.payScene || '') ? (adgroupSceneSpecVo.payScene || '').split(',') : [];
  const wechatPosition = (adgroupSceneSpecVo.wechatPosition || '') ? (adgroupSceneSpecVo.wechatPosition || '').split(',') : [];
  const mobileUnionCategory = (adgroupSceneSpecVo.mobileUnionCategory || '') ? (adgroupSceneSpecVo.mobileUnionCategory || '').split(',') : [];
  const wechatChannelsScene = adgroupSceneSpecVo.wechatChannelsScene ? (adgroupSceneSpecVo.wechatChannelsScene || '').split(',') : [];
  const excludeUnionPositionPackage = (adgroupSceneSpecVo.excludeUnionPositionPackage || '') ? (adgroupSceneSpecVo.excludeUnionPositionPackage || '').split(',') : []
  const unionPositionPackage = (adgroupSceneSpecVo.unionPositionPackage || '') ? (adgroupSceneSpecVo.unionPositionPackage || '').split(',') : [];
  // console.log(adgroupSceneSpecVo.wechatChannelsScene, 'wechatChannelsScene', wechatChannelsScene);
  const advPosition = new Position({
    siteSet: info.siteSet.split(',').map(_ => +_),
    siteSetType: info.siteSetType,
    scene_spec: {
      wechat_scene: {
        // CUSTOM => 自定义 'NONE' => 不限
        type: officialAccountMediaCategory.length || officialAccountMediaCategory.length || miniProgramAndMiniGame.length ? 'CUSTOM' : 'NONE',
        official_account_media_category: officialAccountMediaCategory,
        mini_program_and_mini_game: miniProgramAndMiniGame,
        pay_scene: payScene
      },
      flow_optimization_enabled: adgroupSceneSpecVo.flowOptimizationEnabled,
      // wechat_position
      wechat_position: {
        type: wechatPosition.length ? 'CUSTOM' : 'NONE',
        value: wechatPosition
      },
      mobile_union_category: {
        type: mobileUnionCategory.length ? 'CUSTOM' : 'NONE',
        value: mobileUnionCategory
      },
      qbsearch_scene: {
        type: 'NONE',
        value: []
      },
      wechat_channels_scene: {
        type: wechatChannelsScene.length ? 'CUSTOM' : 'NONE',
        value: wechatChannelsScene
      },
      display_scene: {
        type: 'NONE',
        value: []
      },
      tencent_news: {
        type: 'NONE',
        value: [],
      },
      exclude_union_position_package: {
        type: excludeUnionPositionPackage.length ? 'CUSTOM' : 'NONE',
        value: excludeUnionPositionPackage
      },
      union_position_package: {
        type: unionPositionPackage.length ? 'CUSTOM' : 'NONE',
        value: unionPositionPackage
      },
      exclude_mobile_union: {
        type: 'NONE',
        value: []
      },
      mobile_union: {
        type: 'NONE',
        value: []
      }

    }

  });
  state.modal.position = advPosition;
  // 定向选择
  const targetInfo = JSON.parse(info.targetingInfo || "{}");

  const diect = new Diect({});
  diect.back(targetInfo);
  diect.outTargetingId = info.outTargetingId;
  diect.targetingAccountCode = info.targetingAccountCode;

  state.modal.diect = diect;
  // market 营销内容
  const market = new Market({
    marketingTargetType: info.marketingTargetType,
    marketingGoal: info.marketingGoal,
  });


  state.modal.market = market;
  // 排期

  const schedulePrice = new SchedulePrice({
    releaseDateType: info.releaseDateType,
    releaseTimeType: info.releaseTimeType,
    releaseBeginDate: info.releaseBeginDate,
    releaseEndDate: info.releaseEndDate,
    firstDayBeginTime: info.firstDayBeginTime,
    deepConversionGoal: info.deepConversionGoal,

    releaseBeginTime: info.releaseBeginTime,
    releaseEndTime: info.releaseEndTime,
    bidMode: info.bidMode,
    optimizationGoal: info.optimizationGoal,
    bidScene: info.bidScene,
    dailyBudget: info.dailyBudget,
    bidAmount: info.bidAmount,
    autoAcquisitionEnabled: info.autoAcquisitionEnabled,
    // 单位为分
    autoAcquisitionBudget: info.autoAcquisitionBudget,
    deepConversionSpec: info.deepConversionSpec,
    deepOptimalWarn: info.deepConversionFailTry,
    deepConversionType: info.deepConversionType,
    deepConversionExpectedRoi: info.deepConversionExpectedRoi,
    releaseDate: info.releaseBeginDate ? [Number(new Date(info.releaseBeginDate)), Number(new Date(info.releaseEndDate))] : [Date.now(), Date.now()]
  });
  // console.log('info.deepConversionExpectedRo', info.deepConversionGoal)
  state.modal.schedulePrice = schedulePrice;

  state.accounts = [];
  info.accountAdgroupVoList.map((account: any) => {
    const market = new Market({
      productInfo: {
        productId: account.productId,
        productCatalogId: account.productCatalogId
      }
    });
    const _account = new Account({
      market,
      disabled: true,
      accountCode: account.accountCode,
      accountName: account.accountName,
      wechatChannels: {
        id: account.wechatChannels,
      }
    });
    _account.jumpInfo = [];
    state.accounts.push(
      _account
    )
  });
}






export {
  createAdvBody
}
